/**
 * Author:  LiShibin.
 * Date:    2016/9/22.
 * File：   webpack-dev-middlewar 插件的代理，ehome接口的post请求.
 */
import * as axios from 'axios'
import getHead from './getHead'
import {getErrorCn} from './errorMap'
import {isEmptyObject} from '../util'
import qs from 'qs'
import MessageBox from '@/components/message'

/**
 * 基于axios,自定义的post方法
 * @param type oauth/inner/outer
 * @param url
 * @param data
 * @returns {Promise}
 */
async function post (type, url, data, sec) {
  sec = sec ? 'true' : 'false'
  // console.debug('请求参数：')
  // console.debug(data)
  let serverHost = localStorage.getItem('serverHost')
  let serverHostET = localStorage.getItem('serverHostET')
  // let qiMengJiaHost = 'http://192.168.254.1'
  let serverPort = localStorage.getItem('serverPort')
  let serverPortET = localStorage.getItem('serverPortET')
  let superMapServerHost = localStorage.getItem('superMapServerHost')
  let superMapServerPort = localStorage.getItem('superMapServerPort')
  /**
   * 支持跨域直接访问请求服务器 qt使用
   */
  let proxyUrl = ''
  switch (type) {
    case 'superMap':
      proxyUrl = superMapServerHost + ':' + superMapServerPort + url
      break
    case 'outer':
      proxyUrl = serverHost + ':9000'
      break
    case 'workflow':
      proxyUrl = serverHost + ':9100'
      break
    case 'inner':
      proxyUrl = serverHost + ':9300'
      break
    case 'oauth':
      proxyUrl = serverHost + ':9200'
      break
    case 'swagger':
      proxyUrl = serverHost + ':' + serverPort + url
      break
    case 'swaggerTest':
      proxyUrl = 'http://192.168.254.73' + ':' + serverPort + url
      break
    case 'swaggerET':
      proxyUrl = serverHostET + ':' + serverPortET + url
      break
    default:
      proxyUrl = serverHost + ':9000'
      break
  }
  let head = await getHead(type, url, data)
  data = (['swagger', 'superMap', 'swaggerET', 'swaggerTest'].indexOf(type) < 0) ? encodeURIComponent(JSON.stringify(data)) : data
  if (type === 'superMap') {
    head = {
      'Accept': 'application/json, text/javascript, */*; q=0.01',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
    data = qs.stringify(data)
  }
  return new Promise((resolve, reject) => {
    axios.post(proxyUrl, data, {headers: head}).then(function (response) {
      //  console.log('response:', response)
      if (type === 'superMap') {
        resolve(response.data)
        return
      }
      if (!isEmptyObject(response.data)) {
        if (type !== 'swagger' && type !== 'swaggerET' && type !== 'swaggerTest') {
          let str = response.data.replace(/\+/g, '%20')// 解决空格变成加号的问题
          response.data = decodeURIComponent(str)
          response.data = response.data.replace(/\t/g, '')// 解决制表符影响json解析的问题
        }
        // console.debug('请求结果：')
        // console.debug(response.data)
        // 由于接口设计问题，部分错误会返回一个 ERR_开头的异常信息字符串,如：ERR_{code:'',msg:''}
        if (/ERR_/.test(response.data)) {
          let errorJson = JSON.parse(response.data.replace('ERR_{', '{'))
          // 将英文错误提示映射为中文
          let errorCn = getErrorCn(errorJson.msg)
          if (errorCn) {
            errorJson.msg = errorCn
          }
          MessageBox(errorJson.msg, '提示')
          reject(new Error(JSON.stringify(errorJson)))
        } else if (response.data == null || response.data === '') {
          MessageBox('请求无响应', '提示')
          reject(new Error({code: '4040', msg: '请求无响应'}))
        } else {
          let responseData = (type !== 'swagger' && type !== 'swaggerET' && type !== 'swaggerTest') ? JSON.parse(response.data) : response.data
          // 同时出现code与msg,说明服务端响应的是异常信息
          if (typeof responseData.code !== 'undefined' && typeof responseData.msg !== 'undefined') {
            // 将英文错误提示映射为中文
            let errorCn = getErrorCn(responseData.msg)
            if (errorCn) {
              responseData.msg = errorCn
            }
            MessageBox(responseData.msg, '提示')
            reject(new Error(responseData))
          } else {
            // 正常响应处理
            resolve(responseData)
          }
        }
      } else {
        resolve(response.data)
      }
    }).catch(function (error) {
      console.error('请求服务器发生错误：')
      console.error(error)
      MessageBox('请求失败', '提示')
      reject(new Error({code: '4040', msg: '请求失败'}))
    })
  })
}
export default post
